﻿#include <zyD2DRenderer.h>
#include <iostream>

// 创建设备资源（工厂、渲染目标、画刷等）
void BlackMoonUI::zyD2DRenderer::CreateDeviceResources() {
    // 如果已有资源先释放
    SafeRelease(m_pRenderTarget);
    SafeRelease(m_pDefaultBrush);

    // 1. 创建D2D工厂（如果不存在）
    if (!m_pD2DFactory) {
        HRESULT hr = D2D1CreateFactory(
            D2D1_FACTORY_TYPE_SINGLE_THREADED,
            __uuidof(ID2D1Factory1),
            nullptr,
            (void**)&m_pD2DFactory
        );
        //if (FAILED(hr)) throw std::runtime_error("D2D工厂创建失败");
    }

    // 2. 创建DirectWrite工厂（如果不存在）
    if (!m_pDWriteFactory) {
        HRESULT hr = DWriteCreateFactory(
            DWRITE_FACTORY_TYPE_SHARED,
            __uuidof(IDWriteFactory),
            (IUnknown**)&m_pDWriteFactory
        );
        if (FAILED(hr)) {
            SafeRelease(m_pD2DFactory);
            //throw std::runtime_error("DWrite工厂创建失败");
        }
    }

    // 3. 创建窗口关联的渲染目标
    D2D1_RENDER_TARGET_PROPERTIES renderTargetProps = D2D1::RenderTargetProperties(
        D2D1_RENDER_TARGET_TYPE_DEFAULT,          // 使用硬件加速
        D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
        96.0f, 96.0f,                             // 匹配系统 DPI
        D2D1_RENDER_TARGET_USAGE_NONE,
        D2D1_FEATURE_LEVEL_DEFAULT
    );

    D2D1_HWND_RENDER_TARGET_PROPERTIES hwndProps = D2D1::HwndRenderTargetProperties(m_hWnd, m_size);

    HRESULT hr = m_pD2DFactory->CreateHwndRenderTarget(
        &renderTargetProps,
        &hwndProps,
        &m_pRenderTarget
    );
    if (FAILED(hr)) {
        SafeRelease(m_pD2DFactory);
        SafeRelease(m_pDWriteFactory);
        //throw std::runtime_error("渲染目标创建失败");
    }
    m_pRenderTarget->SetAntialiasMode(D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);//抗锯齿
    // 4. 创建默认画刷
    hr = m_pRenderTarget->CreateSolidColorBrush(
        D2D1::ColorF(D2D1::ColorF::Black),
        &m_pDefaultBrush
    );
    if (FAILED(hr)) {
        SafeRelease(m_pRenderTarget);
        SafeRelease(m_pD2DFactory);
        SafeRelease(m_pDWriteFactory);
        //throw std::runtime_error("默认画刷创建失败");
    }
}

// 构造函数
BlackMoonUI::zyD2DRenderer::zyD2DRenderer(HWND hWnd, UINT width, UINT height)
    : m_hWnd(hWnd), m_size({ width, height }),
    m_pD2DFactory(nullptr),
    m_pDWriteFactory(nullptr),
    m_pRenderTarget(nullptr),
    m_pDefaultBrush(nullptr) {
    CreateDeviceResources();
}

// 析构函数
BlackMoonUI::zyD2DRenderer::~zyD2DRenderer() {
    SafeRelease(m_pDefaultBrush);
    SafeRelease(m_pRenderTarget);
    SafeRelease(m_pDWriteFactory);
    SafeRelease(m_pD2DFactory);
}

// 开始绘制
void BlackMoonUI::zyD2DRenderer::BeginDraw() {
    if (m_pRenderTarget) {
        m_pRenderTarget->BeginDraw();
        m_pRenderTarget->SetAntialiasMode(D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
        m_pRenderTarget->SetTransform(D2D1::Matrix3x2F::Identity());
    }
}

// 结束绘制
void BlackMoonUI::zyD2DRenderer::EndDraw() {
    if (!m_pRenderTarget) return;

    HRESULT hr = m_pRenderTarget->EndDraw();

    // 设备丢失处理
    if (hr == D2DERR_RECREATE_TARGET) {
        SafeRelease(m_pDefaultBrush);
        SafeRelease(m_pRenderTarget);
        CreateDeviceResources();
    }
}

// 清空画布
void BlackMoonUI::zyD2DRenderer::Clear(D2D1_COLOR_F color) {
    if (m_pRenderTarget) {
        m_pRenderTarget->Clear(&color);
    }
}

// 绘制矩形
void BlackMoonUI::zyD2DRenderer::DrawRectangle(const D2D1_RECT_F& rect,
    D2D1_COLOR_F color, float strokeWidth) {
    if (m_pRenderTarget && m_pDefaultBrush) {
        m_pDefaultBrush->SetColor(color);
        m_pRenderTarget->DrawRectangle(rect, m_pDefaultBrush, strokeWidth);
    }
}

// 窗口尺寸调整
void BlackMoonUI::zyD2DRenderer::Resize(UINT width, UINT height) {
    m_size = { width, height };
    if (m_pRenderTarget) {
        HRESULT hr = m_pRenderTarget->Resize(m_size);
        if (FAILED(hr)) {
            SafeRelease(m_pRenderTarget);
        }
    }
}

// 创建文本格式
IDWriteTextFormat* BlackMoonUI::zyD2DRenderer::CreateTextFormat(const WCHAR* fontName, float fontSize,
    DWRITE_FONT_WEIGHT fontWeight,DWRITE_FONT_STYLE fontStyle,DWRITE_FONT_STRETCH fontStretch){
    IDWriteTextFormat* pFormat = nullptr;
    if (m_pDWriteFactory) {
        HRESULT hr = m_pDWriteFactory->CreateTextFormat( fontName, nullptr,fontWeight, fontStyle,
            fontStretch, fontSize, L"",  &pFormat
        );
        if (FAILED(hr)) pFormat = nullptr;
    }
    return pFormat;
}

// 绘制阴影
void BlackMoonUI::zyD2DRenderer::DrawShadow(const D2D1_RECT_F& rect, float cornerRadius, float blurRadius, 
    D2D1_COLOR_F shadowColor, D2D1_POINT_2F shadowOffset, float opacity) {
    D2D1_ROUNDED_RECT roundedRect = D2D1::RoundedRect(rect, cornerRadius, cornerRadius);

    // 创建一个位图渲染目标
    ID2D1BitmapRenderTarget* pBitmapRenderTarget = nullptr;
    HRESULT hr = m_pRenderTarget->CreateCompatibleRenderTarget(&pBitmapRenderTarget);

    if (SUCCEEDED(hr)) {
        // 绘制圆角矩形到位图上
        pBitmapRenderTarget->BeginDraw();
        pBitmapRenderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White, 0.0f)); // 透明背景
        m_pDefaultBrush->SetColor(D2D1::ColorF(D2D1::ColorF::Black, opacity));
        pBitmapRenderTarget->FillRoundedRectangle(roundedRect, m_pDefaultBrush);
        pBitmapRenderTarget->EndDraw();

        // 获取位图
        ID2D1Bitmap* pBitmap = nullptr;
        hr = pBitmapRenderTarget->GetBitmap(&pBitmap);

        if (SUCCEEDED(hr)) {
            // 创建阴影效果
            ID2D1Effect* pShadowEffect = nullptr;
            ID2D1DeviceContext* pDC = nullptr;
            if (SUCCEEDED(m_pRenderTarget->QueryInterface(__uuidof(ID2D1DeviceContext), (void**)&pDC))) {
                if (SUCCEEDED(pDC->CreateEffect(CLSID_D2D1Shadow, &pShadowEffect))) {
                    // 设置阴影参数
                    pShadowEffect->SetInput(0, pBitmap);
                    pShadowEffect->SetValue(D2D1_SHADOW_PROP_COLOR, D2D1::Vector4F(shadowColor.r, shadowColor.g, shadowColor.b, shadowColor.a));
                    pShadowEffect->SetValue(D2D1_SHADOW_PROP_BLUR_STANDARD_DEVIATION, blurRadius);

                    // 绘制阴影（带偏移）
                    pDC->DrawImage(pShadowEffect, shadowOffset);

                    SafeRelease(pShadowEffect);
                }
                SafeRelease(pDC);
            }
            SafeRelease(pBitmap);
        }
        SafeRelease(pBitmapRenderTarget);
    }
}

void BlackMoonUI::zyD2DRenderer::FillRectangle(const D2D1_RECT_F& rect, D2D1_COLOR_F color) {
    m_pDefaultBrush->SetColor(color);
    m_pRenderTarget->FillRectangle(rect, m_pDefaultBrush);
}

void BlackMoonUI::zyD2DRenderer::DrawCircle(D2D1_POINT_2F center, float radius, D2D1_COLOR_F color, float strokeWidth ) {
    m_pDefaultBrush->SetColor(color);
    D2D1_ELLIPSE ellipse = D2D1::Ellipse(center, radius, radius);
    m_pRenderTarget->DrawEllipse(ellipse, m_pDefaultBrush, strokeWidth);
}

void BlackMoonUI::zyD2DRenderer::FillCircle(D2D1_POINT_2F center, float radius, D2D1_COLOR_F color) {
    m_pDefaultBrush->SetColor(color);
    D2D1_ELLIPSE ellipse = D2D1::Ellipse(center, radius, radius);
    m_pRenderTarget->FillEllipse(ellipse, m_pDefaultBrush);
}

void BlackMoonUI::zyD2DRenderer::DrawText(const WCHAR* text,const D2D1_RECT_F& layoutRect,
    IDWriteTextFormat* pFormat, D2D1_COLOR_F color) {
    m_pDefaultBrush->SetColor(color);
    m_pRenderTarget->DrawText(text, wcslen(text), pFormat, layoutRect, m_pDefaultBrush);
}

ID2D1Factory1* BlackMoonUI::zyD2DRenderer::GetD2DFactory1() const { return m_pD2DFactory; }
bool BlackMoonUI::zyD2DRenderer::SetD2DFactory1(ID2D1Factory1* pD2DFactory) {
    // 空指针检查
    if (pD2DFactory == nullptr) {
        return false;
    }

    // 线程安全保护
    //std::lock_guard<std::mutex> lock(m_mutex);

    // 释放旧的工厂对象
    if (m_pD2DFactory) {
        SafeRelease(m_pD2DFactory);
    }

    // 设置新的工厂对象
    m_pD2DFactory = pD2DFactory;

    return true;
}

ID2D1SolidColorBrush* BlackMoonUI::zyD2DRenderer::GetDefaultBrush() const { return m_pDefaultBrush; }

void BlackMoonUI::zyD2DRenderer::FillRoundedRectangle(const D2D1_RECT_F& rect,
    float radiusX, float radiusY, D2D1_COLOR_F color){
    m_pDefaultBrush->SetColor(color);
    D2D1_ROUNDED_RECT roundedRect = D2D1::RoundedRect(rect, radiusX, radiusY);
    m_pRenderTarget->FillRoundedRectangle(roundedRect, m_pDefaultBrush);
}


#include <comdef.h>  // For _bstr_t 或使用 WideCharToMultiByte

//-----------------------------------------------------------------------------
// 加载SVG文件（支持宽字符路径）
//-----------------------------------------------------------------------------
bool BlackMoonUI::zyD2DRenderer::LoadSVG(const wchar_t* filename) {
    // 释放之前加载的资源
    ReleaseSVGResources();

    // 将宽字符路径转换为UTF-8
    _bstr_t bstrFilename(filename);
    const char* utf8Filename = bstrFilename;  // 自动转换为多字节

    // 使用nanosvg解析SVG文件
    m_svgImage = nsvgParseFromFile(utf8Filename, "px", 96.0f);

    // 错误处理
    if (!m_svgImage) {
        DWORD err = GetLastError();
        // 可在此添加日志输出
        // OutputDebugStringW(L"SVG加载失败: ");
        // OutputDebugStringW(filename);
        return false;
    }

    // 预转换几何体
    PrecacheSVG();
    return true;
}

//-----------------------------------------------------------------------------
// 内存加载SVG实现
//-----------------------------------------------------------------------------
bool BlackMoonUI::zyD2DRenderer::LoadSVGFromMemory(const char* svgData) {
    ReleaseSVGResources();
    m_svgImage = nsvgParse((char*)svgData, "px", 96.0f);
    if (!m_svgImage) return false;

    PrecacheSVG();
    return true;
}

//-----------------------------------------------------------------------------
// 资源释放实现
//-----------------------------------------------------------------------------
void BlackMoonUI::zyD2DRenderer::ReleaseSVGResources() {
    // 释放nanosvg资源
    if (m_svgImage) {
        nsvgDelete(m_svgImage);
        m_svgImage = nullptr;
    }

    // 释放Direct2D资源
    for (auto& shape : m_shapeCache) {
        SafeRelease(shape.geometry);
        SafeRelease(shape.fillBrush);
        SafeRelease(shape.strokeBrush);
    }
    m_shapeCache.clear();

    for (auto& pair : m_gradientBrushes) {
        SafeRelease(pair.second);
    }
    m_gradientBrushes.clear();
}
void BlackMoonUI::zyD2DRenderer::DrawSVG(float x, float y) {
    if (!m_svgImage) return;  // 确保 SVG 已加载
    // 直接调用修改后的 DrawSVG 函数，关闭自动缩放并指定原始尺寸
    DrawSVGScale(x,y,
        m_svgImage->width,   // 目标宽度 = SVG 原始宽度
        m_svgImage->height,  // 目标高度 = SVG 原始高度
        false                // 禁用自动缩放
    );
}
// 自动缩放实现
void BlackMoonUI::zyD2DRenderer::DrawSVGScale(float x, float y, float targetWidth, float targetHeight, bool autoScale) {
    if (!m_svgImage || !m_pRenderTarget) return;

    float scaleX = 1.0f;
    float scaleY = 1.0f;

    if (autoScale) {
        // 自动缩放逻辑：适应渲染目标剩余区域
        D2D1_SIZE_F rtSize = m_pRenderTarget->GetSize();
        scaleX = (rtSize.width - x) / m_svgImage->width;
        scaleY = (rtSize.height - y) / m_svgImage->height;
        float scale = min(scaleX, scaleY);
        scaleX = scale;
        scaleY = scale;
    }
    else {
        // 手动指定大小：根据目标尺寸计算缩放比例
        if (targetWidth > 0) {
            scaleX = targetWidth / m_svgImage->width;
        }
        if (targetHeight > 0) {
            scaleY = targetHeight / m_svgImage->height;
        }
        // 若需保持宽高比，可在此处统一 scaleX 和 scaleY
        // float scale = min(scaleX, scaleY);
        // scaleX = scaleY = scale;
    }

    // 构建变换矩阵（先缩放后平移）
    D2D1::Matrix3x2F transform =
        D2D1::Matrix3x2F::Scale(scaleX, scaleY) *
        D2D1::Matrix3x2F::Translation(x, y);

    m_pRenderTarget->SetTransform(transform);

    // 绘制缓存的几何图形
    for (const auto& shape : m_shapeCache) {
        if (shape.fillBrush) {
            m_pRenderTarget->FillGeometry(shape.geometry, shape.fillBrush);
        }
        if (shape.strokeBrush && shape.strokeWidth > 0) {
            m_pRenderTarget->DrawGeometry(shape.geometry, shape.strokeBrush, shape.strokeWidth);
        }
    }
    // 重置变换矩阵
    m_pRenderTarget->SetTransform(D2D1::Matrix3x2F::Identity());
}

// 渐变色支持实现
ID2D1Brush* BlackMoonUI::zyD2DRenderer::CreateGradientBrush(const NSVGshape* grad) {
    if (!grad || !m_pRenderTarget) return nullptr;

    // 获取填充或描边的渐变数据
    NSVGpaint paint = grad->fill; // 默认为填充渐变
    if (paint.type != NSVG_PAINT_LINEAR_GRADIENT && paint.type != NSVG_PAINT_RADIAL_GRADIENT) {
        paint = grad->stroke; // 如果填充不是渐变，检查描边
        if (paint.type != NSVG_PAINT_LINEAR_GRADIENT && paint.type != NSVG_PAINT_RADIAL_GRADIENT) {
            return nullptr;
        }
    }
    // 检查渐变数据是否有效
    if (!grad->fill.gradient || grad->fill.gradient->nstops == 0) {
        return nullptr;
    }

    // 创建渐变停止点
    std::vector<D2D1_GRADIENT_STOP> stops;
    for (int i = 0; i < grad->fill.gradient->nstops; ++i) {
        stops.push_back(D2D1::GradientStop(
            grad->fill.gradient->stops[i].offset,
            ParseNSVGColor(
                grad->fill.gradient->stops[i].color,
                grad->opacity
            )
        ));
    }

    // 创建渐变集合
    ID2D1GradientStopCollection* collection = nullptr;
    HRESULT hr = m_pRenderTarget->CreateGradientStopCollection(
        stops.data(),
        stops.size(),
        D2D1_GAMMA_2_2,
        D2D1_EXTEND_MODE_CLAMP,
        &collection
    );
    if (FAILED(hr) || !collection) {
        return nullptr;
    }

    // 创建线性/径向渐变
    ID2D1Brush* brush = nullptr;
    if (grad->fill.type == NSVG_PAINT_LINEAR_GRADIENT) {
        ID2D1LinearGradientBrush* lgBrush;
        D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props = {
            D2D1::Point2F(grad->xform[4], grad->xform[5]), // 起点
            D2D1::Point2F(grad->xform[4] + grad->xform[0], // 终点
                         grad->xform[5] + grad->xform[3])
        };
        hr = m_pRenderTarget->CreateLinearGradientBrush(
            props,
            collection,
            &lgBrush
        );
        if (SUCCEEDED(hr)) {
            brush = lgBrush;
        }
    }
    else if (grad->fill.type == NSVG_PAINT_RADIAL_GRADIENT) {
        ID2D1RadialGradientBrush* rgBrush;
        NSVGgradient* nsgrad = grad->fill.gradient;
        // 计算半径
        float fx = grad->xform[4]; // 平移分量 tx
        float fy = grad->xform[5]; // 平移分量 ty
        float r = sqrtf(grad->xform[0] * grad->xform[0] + grad->xform[3] * grad->xform[3]);
        D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props = {
            D2D1::Point2F(fx, fy),  // 焦点位置
            D2D1::Point2F(0, 0),                    // 中心偏移
            r,                              // X半径
            r                               // Y半径
        };
        hr = m_pRenderTarget->CreateRadialGradientBrush(
            props,
            collection,
            &rgBrush
        );
        if (SUCCEEDED(hr)) {
            brush = rgBrush;
            // ⭐ 应用形状的变换矩阵到画刷 ⭐
            D2D1::Matrix3x2F shapeXform(
                grad->xform[0], grad->xform[1],
                grad->xform[2], grad->xform[3],
                grad->xform[4], grad->xform[5]
            );
            rgBrush->SetTransform(shapeXform);
        }
    }

    // 释放渐变集合
    collection->Release();

    return brush;
}

// 性能优化：预转换几何体
void BlackMoonUI::zyD2DRenderer::PrecacheSVG() {
    if (!m_svgImage) return;

    // 清理旧缓存
    for (auto& shape : m_shapeCache) {
        SafeRelease(shape.geometry);
        SafeRelease(shape.fillBrush);
        SafeRelease(shape.strokeBrush);
    }
    m_shapeCache.clear();

    // 遍历所有形状
    for (NSVGshape* shape = m_svgImage->shapes; shape; shape = shape->next) {
        // 处理填充       
        ID2D1Brush* fillBrush = nullptr;
        if (shape->fill.type != NSVG_PAINT_NONE) {
            if (shape->fill.type == NSVG_PAINT_COLOR) {
                // 创建纯色画刷
                D2D1_COLOR_F color = ParseNSVGColor(shape->fill.color, shape->opacity);
                std::wcout << shape->opacity << L"  Shape Fill Type: " << color.a << std::endl;
                HRESULT hr = m_pRenderTarget->CreateSolidColorBrush(color,
                    reinterpret_cast<ID2D1SolidColorBrush**>(&fillBrush)
                );
                if (FAILED(hr)) {
                    // 错误处理：画刷创建失败
                    std::wcout << L"Shape Fill Type: " << shape->fill.type << std::endl;
                    fillBrush = nullptr;
                }
            }
            else if (shape->fill.type == NSVG_PAINT_LINEAR_GRADIENT ||shape->fill.type == NSVG_PAINT_RADIAL_GRADIENT) {
                fillBrush = CreateGradientBrush(shape);
            }
        }

        // 处理描边
        ID2D1Brush* strokeBrush = nullptr;
        if (shape->stroke.type != NSVG_PAINT_NONE) {
            if (shape->stroke.type == NSVG_PAINT_COLOR) {
                m_pRenderTarget->CreateSolidColorBrush(
                    ParseNSVGColor(shape->stroke.color, shape->opacity),
                    reinterpret_cast<ID2D1SolidColorBrush**>(&strokeBrush)
                );
            }
            else if (shape->stroke.type == NSVG_PAINT_LINEAR_GRADIENT || shape->stroke.type == NSVG_PAINT_RADIAL_GRADIENT) {
                strokeBrush = CreateGradientBrush(shape);
            }
        }

        // 转换路径
        for (NSVGpath* path = shape->paths; path; path = path->next) {
            if (ID2D1Geometry* geom = ConvertPath(path, shape)) {
                CachedShape cached = {geom,fillBrush, strokeBrush, shape->strokeWidth};

                // 保持引用计数
                if (fillBrush) fillBrush->AddRef();
                if (strokeBrush) strokeBrush->AddRef();

                m_shapeCache.push_back(cached);
            }
        }

        // 释放临时画刷
        SafeRelease(fillBrush);
        SafeRelease(strokeBrush);
    }
}

// 路径转换实现（修复填充规则问题）
ID2D1Geometry* BlackMoonUI::zyD2DRenderer::ConvertPath(NSVGpath* path, const NSVGshape* shape) {
    ID2D1PathGeometry* geometry = nullptr;
    m_pD2DFactory->CreatePathGeometry(&geometry);

    ID2D1GeometrySink* sink = nullptr;
    if (SUCCEEDED(geometry->Open(&sink))) {
        // 设置填充规则
        sink->SetFillMode(shape->fillRule == NSVG_FILLRULE_EVENODD ?
            D2D1_FILL_MODE_ALTERNATE : D2D1_FILL_MODE_WINDING);
        for (NSVGpath* path = shape->paths; path; path = path->next) {
            if (path->npts < 4) continue;

            sink->BeginFigure(
                D2D1::Point2F(path->pts[0], path->pts[1]),
                D2D1_FIGURE_BEGIN_FILLED
            );

            for (int i = 1; i < path->npts; i += 3) {
                if (i + 2 >= path->npts) break;

                const float* p = &path->pts[i * 2];
                sink->AddBezier(D2D1::BezierSegment(
                    { p[0], p[1] },
                    { p[2], p[3] },
                    { p[4], p[5] }
                ));
            }

            sink->EndFigure(path->closed ?
                D2D1_FIGURE_END_CLOSED : D2D1_FIGURE_END_OPEN);
        }
              

        sink->Close();
        sink->Release();

        // 应用变换矩阵
        D2D1::Matrix3x2F transform(
            shape->xform[0], shape->xform[1],
            shape->xform[2], shape->xform[3],
            shape->xform[4], shape->xform[5]
        );

        ID2D1TransformedGeometry* transformedGeo = nullptr;
        if (FAILED(m_pD2DFactory->CreateTransformedGeometry(
            geometry, &transform, &transformedGeo))) {
            geometry->Release();
            return nullptr;
        }

        geometry->Release();
        return transformedGeo;
    }
    return nullptr;
}

// 颜色解析
D2D1_COLOR_F BlackMoonUI::zyD2DRenderer::ParseNSVGColor(unsigned int color, float opacity) {
    //color 10进制颜色
    return D2D1::ColorF(
        ((color >> 0) & 0xFF) / 255.0f,   //r
        ((color >> 8) & 0xFF) / 255.0f,   //g
        ((color >> 16) & 0xFF) / 255.0f,   //b
        ((color >> 24) & 0xFF) / 255.0f * opacity // Alpha
    );
}

// 交互高亮函数（优化版）
void BlackMoonUI::zyD2DRenderer::DrawSVGWithInteraction(D2D1_POINT_2F mousePos) {
    if (!m_pRenderTarget || m_shapeCache.empty()) return;

    // 获取当前变换并计算逆矩阵
    D2D1_MATRIX_3X2_F currentTransform;
    m_pRenderTarget->GetTransform(&currentTransform);
    D2D1::Matrix3x2F inverseTransform;

    // 转换鼠标坐标到局部空间
    inverseTransform.TransformPoint(mousePos);

    // 检查并高亮悬停路径
    for (auto& shape : m_shapeCache) {
        BOOL contains = FALSE;
        if (SUCCEEDED(shape.geometry->FillContainsPoint(mousePos, D2D1::Matrix3x2F::Identity(), &contains)) && contains) {
            ID2D1SolidColorBrush* m_pHighlightBrush = nullptr;
            m_pRenderTarget->CreateSolidColorBrush(
                D2D1::ColorF(D2D1::ColorF::Yellow, 0.3f),
                &m_pHighlightBrush
            );
            m_pRenderTarget->FillGeometry(shape.geometry, m_pHighlightBrush);
            // 释放临时画刷
            SafeRelease(m_pHighlightBrush);
        }
    }
}

// 动画函数（优化版）
void BlackMoonUI::zyD2DRenderer::AnimateSVG(float time) {
    if (!m_pRenderTarget) return;

    // 保存原始变换
    D2D1_MATRIX_3X2_F originalTransform;
    m_pRenderTarget->GetTransform(&originalTransform);

    // 计算绕中心点旋转的变换矩阵
    float centerX = 100.0f + m_svgImage->width / 2.0f;
    float centerY = 100.0f + m_svgImage->height / 2.0f;
    D2D1::Matrix3x2F matrix =
        D2D1::Matrix3x2F::Translation(centerX, centerY) *
        D2D1::Matrix3x2F::Rotation(time * 30.0f) *
        D2D1::Matrix3x2F::Translation(-m_svgImage->width / 2.0f, -m_svgImage->height / 2.0f);

    m_pRenderTarget->SetTransform(matrix);
    DrawSVGScale(0.0f, 0.0f, m_svgImage->width, m_svgImage->height, false); // 按原始尺寸绘制

    m_pRenderTarget->SetTransform(originalTransform);
}
